package com.gujiangbo.sentinel.controller;

import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class TestBooleanController {

    @GetMapping("booleanSayHello")
    public String booleanSayHello() {

        //1.进行限流控制
        if (SphO.entry("boolean")) {//限流入口
            try {
                //被保护的资源
                System.out.println("访问成功");
                return "访问成功！";
            } finally {
                //sphO.entry(xxx)需要与SphO.exit()方法成对出现，否则会导致调用链记录异常，抛出ErrorEntryFreeException异常
                SphO.exit();
            }
        } else {
            //被限流或者降级的处理
            System.out.println("系统繁忙，请稍后再试！");
            return "系统繁忙，请稍后再试！";
        }
    }

    @PostConstruct
    public void initFlowRules() {
        List<FlowRule> flowRules = new ArrayList<FlowRule>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("boolean");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(2);
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);
    }

}
